package com.aimusic.Handler;

import com.aimusic.Exception.BusinessException;
import com.aimusic.domain.Result;
import com.aimusic.enums.ErrorCode;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result handleBusinessException(BusinessException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        
        // 获取所有校验失败的字段和信息
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        
        return Result.error(ErrorCode.PARAM_VALID_ERROR.getCode(),
                           ErrorCode.PARAM_VALID_ERROR.getMessage(), 
                           errorMap);
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(Exception e, HttpServletRequest request) {
        // 可以在这里记录异常日志
        System.err.println("系统异常: " + e.getMessage());
        e.printStackTrace();
        
        // 生产环境可以返回更友好的信息，隐藏具体异常
        String message = "系统繁忙，请稍后再试";
        // 开发环境可以显示具体异常信息
        if ("dev".equals(getProfile())) {
            message = e.getMessage();
        }
        
        return Result.error(ErrorCode.SYSTEM_ERROR.getCode(), message);
    }
    
    /**
     * 获取当前环境（实际项目中可以从配置中获取）
     */
    private String getProfile() {
        // 实际应用中可以从环境变量或配置文件中获取
        return "dev";
    }
}
    